<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\Order;
use App\Models\User;
use Carbon\Carbon;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Yansongda\Pay\Log as debugLog;
use Yansongda\Pay\Pay;

class PayController extends Controller {
	private $wx_config;
	private $alipay;
	private $user_id;
	public function __construct() {
		if (\Auth::guard('api')->check()) {
			$user = \Auth::guard('api')->user();
			$this->user_id = $user->id;
		}
		$this->wx_config = Config::get('pay.wechat');
		$this->alipay = Config::get('pay.alipay');
	}
	//生成订单
	public function index(Request $request) {
		$payType = $request->input('payType');
		if (!in_array($payType, [1, 2])) {
			return $this->respond('empty_error');
		}
		$user = User::find($this->user_id);
		if (empty($user)) {
			$this->respond('get_error');
		}
		$company = Company::where(['status' => 0, 'id' => $user->company_id])->select('order_num', 'order_updated_at')->first()->toArray();
		$type = $request->input('type'); //1:购买 2：续费
		$num = $request->input('num');
		$year = $request->input('year');
		if (!in_array($type, [1, 2]) || !is_numeric($year) || ($type == 1 && !is_numeric($num))) {
			return $this->respond('empty_error');
		}
		if ($type == 2) {
			$num = $company['order_num'];
		}
		if ($year > 99 || $num > 99) {
			return $this->respond('empty_error');
		}
		$date1 = $company['order_updated_at'];
		$date2 = strtotime('+' . $year . ' year');
		if ($type == 1 && ($date2 <= $date1)) {
			return response()->json(['code' => 500, 'msg' => '新账号到期时间小于旧账号到期时间，不允许购买']);
		}
		$price = $this->getOrderPrice($type, $num, $year, $company);
		$order_no = date('YmdHis') . mt_rand(100000, 999999);
		$name = 'ATS专业版';
		$order_data = [
			'userId' => $this->user_id,
			'companyId' => $user->company_id,
			'name' => $name,
			'orderNo' => $order_no,
			'num' => $num,
			'term' => $year,
			'flag' => $type,
			'price' => $price,
			'type' => $payType,
		];
		\Log::info('生成订单开始');
		//微信支付
		//
		if ($payType == 1) {
			$order = [
				'out_trade_no' => $order_no,
				'total_fee' => env('PAY_TEST') == true ? 1 : $price * 100,
				'body' => $name,
			];
			try {
				Order::create($order_data);
				$pay = Pay::wechat($this->wx_config);
				$result = $pay->scan($order);
				if (!empty($result)) {
					\Log::info('生成微信订单成功');
					$qr = $result->code_url;
					return $this->respond('op_ok', ['code_url' => $qr, 'order_no' => $order_no]);
				}
			} catch (Exception $e) {
				\Log::info('支付调起失败:', $e->getMessage());
			}
		} else if ($payType == 2) {
			//支付宝支付
			try {
				$order = [
					'out_trade_no' => $order_no,
					'total_amount' => env('PAY_TEST') == true ? 0.01 : $price,
					'subject' => $name,
				];
				Order::create($order_data);
				\Log::info('生成支付宝订单成功');
				$result = Pay::alipay($this->alipay)->web($order);
				return response($result);

			} catch (GatewayException $e) {
				\Log::info('支付调起失败:', $e->getMessage());
			}
		}
	}
	//去支付
	public function gopay(Request $request) {
		$id = $request->input('id');
		$payType = $request->input('payType');
		if (empty($id) || empty($payType)) {
			return $this->respond('empty_error');
		}
		if (!in_array($payType, [1, 2])) {
			return $this->respond('empty_error');
		}
		$item = Order::find($id);
		if (empty($item)) {
			return $this->respond('get_error');
		}
		$item->timestamps = false;
		$item->type = $payType;
		$item->save();
		//微信支付
		if ($payType == 1) {
			$total_price = ($item->price) * 100;
			$order = [
				'out_trade_no' => $item->orderNo,
				'total_fee' => env('PAY_TEST') == true ? 1 : $total_price,
				'body' => $item->name,
			];
			try {
				$pay = Pay::wechat($this->wx_config);
				$result = $pay->scan($order);
				if (!empty($result)) {
					\Log::info('微信去支付订单成功');
					$qr = $result->code_url;
					return $this->respond('get_ok', ['code_url' => $qr, 'order_no' => $item->orderNo]);
				}
			} catch (Exception $e) {
				$e->getMessage();
			}
		} else if ($payType == 2) {
			//支付宝支付
			try {
				$order = [
					'out_trade_no' => $item->orderNo,
					'total_amount' => env('PAY_TEST') == true ? 0.01 : $item->price,
					'subject' => $item->name,
				];
				$result = Pay::alipay($this->alipay)->web($order);
				return response($result);

			} catch (GatewayException $e) {
				\Log::info('支付调起失败:', $e->getMessage());
			}
		}
	}

	public function notifyUrl() {
		\Log::info('支付宝支付异步回调开始:', ['date' => date('Y-m-d H:i:s')]);
		$alipay = Pay::alipay($this->alipay);
		try {
			$data = $alipay->verify(); // 是的，验签就这么简单！
			debugLog::debug('Alipay notify', $data->all());
			if ($data->trade_status == 'TRADE_SUCCESS' || $data->trade_status == 'TRADE_FINISHED') {
				$order_no = $data->out_trade_no;
				$order = Order::where('orderNo', $order_no)->first();
				if (!empty($order)) {
					$year = $order->term;
					$vdate = strtotime('+' . $year . ' year');
					$order->validity = $vdate;
					$order->status = 2;
					$order->outTradeNo = $data->trade_no;
					//公司表
					$company = Company::where(['status' => 0, 'id' => $order->companyId])->first();
					if ($order->flag == 1) {
						//购买
						$company->order_num = $company->order_num + $order->num;
						$company->order_updated_at = $vdate;
					} else if ($order->flag == 2) {
						//续费
						$get_date = $company->order_updated_at;
						if ($get_date > time()) {
							$company->order_updated_at = strtotime('+' . $year . ' year', $company->order_updated_at);
						} else {
							$company->order_updated_at = $vdate;
						}
					}
					$order->save();
					$company->save();
					return $alipay->success();
				}
			}
			\Log::info("支付宝支付回调成功", ['out_trade_no' => $data->out_trade_no, 'trade_status' => $data->trade_status]);
		} catch (Exception $e) {
			$e->getMessage();
		}
		\Log::info('支付宝支付异步回调结束:', ['date' => date('Y-m-d H:i:s')]);
	}
	public function returnUrl() {
		\Log::info('支付同步回调成功:', ['date' => date('Y-m-d H:i:s')]);
		dd('支付同步回调成功 date:' . date('Y-m-d H:i:s'));
	}
	//获取订单信息
	public function info(Request $request) {
		$user = User::find($this->user_id);
		if (empty($user)) {
			$this->respond('get_error');
		}
		$staff = \App\Models\Staff::where(['status' => 0, 'company_id' => $user->company_id, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		$roleType = $request->input('roleType');
		if ($roleType == 1) {
			if (empty($staff)) {
				return response()->json(['code' => 403, 'msg' => '您没有购买权限，请联系管理员购买']);
			}
			return $this->respond('op_ok');
		}
		if (empty($staff)) {
			return $this->respond('no_auth');
		}
		$company = Company::where(['status' => 0, 'id' => $user->company_id])->select('order_num', 'order_updated_at')->first()->toArray();
		$company['date'] = time();
		if (!empty($company)) {
			return response()->json(['code' => 200, 'data' => $company]);
		}
		$this->respond('get_error');
	}
	//计算订单价格
	public function orderPrice(Request $request) {
		$price = 0.00;
		$user = User::find($this->user_id);
		if (empty($user)) {
			$this->respond('get_error');
		}
		$company = Company::where(['status' => 0, 'id' => $user->company_id])->select('order_num', 'order_updated_at')->first()->toArray();
		$type = $request->input('type');
		$num = $request->input('num');
		$year = $request->input('year');
		if (!in_array($type, [1, 2]) && !is_numeric($year)) {
			return $this->respond('empty_error');
		}
		$date1 = $company['order_updated_at'];
		$date2 = strtotime('+' . $year . ' year');
		if ($type == 1 && ($date2 <= $date1)) {
			return response()->json(['code' => 500, 'msg' => '新账号到期时间小于旧账号到期时间，不允许购买']);
		}
		$price = $this->getOrderPrice($type, $num, $year, $company);
		return $this->respond('get_ok', ['price' => $price]);
	}
	private function getOrderPrice($type, $num, $year, $company) {
		$price = 0.00;
		if ($type == 1) {
			// 购买
			if ($company['order_num'] > 0) {
				$date1 = $company['order_updated_at'];
				$p = sprintf("%.2f", $num * $year * 8000);
				if ($date1 < time()) {
					//是否过期
					$p1 = sprintf("%.2f", $company['order_num'] * 8000 * $year);
				} else {
					$end = Carbon::createFromTimestamp($date1);
					$date2 = strtotime('+' . $year . ' year');
					$date1 = Carbon::createFromTimestamp($date2);
					$days = $end->diffInDays($date1, false);
					$p1 = sprintf("%.2f", $company['order_num'] * 8000 / 365 * $days);
				}
				$price = $p + $p1;

			} else {

				$price = sprintf("%.2f", $num * $year * 8000);
			}

		} else if ($type == 2) {
			//续费
			$price = sprintf("%.2f", $company['order_num'] * $year * 8000);
		}
		return sprintf("%.2f", $price);
	}

	public function notifyWxUrl() {
		\Log::info('微信支付异步回调开始:', ['date' => date('Y-m-d H:i:s')]);
		$pay = Pay::wechat($this->wx_config);

		try {
			$data = $pay->verify(); // 是的，验签就这么简单！
			\Log::info('微信支付回调数据:', ['info' => json_encode($data->all())]);
			debugLog::debug('Wechat notify', $data->all());
			if ($data->result_code == 'SUCCESS' && $data->return_code == 'SUCCESS') {
				$order_no = $data->out_trade_no;
				$order = Order::where('orderNo', $order_no)->first();
				if (!empty($order)) {
					$year = $order->term;
					$vdate = strtotime('+' . $year . ' year');
					$order->validity = $vdate;
					$order->status = 2;
					$order->outTradeNo = $data->transaction_id;
					//公司表
					$company = Company::where(['status' => 0, 'id' => $order->companyId])->first();
					if ($order->flag == 1) {
						//购买
						$company->order_num = $company->order_num + $order->num;
						$company->order_updated_at = $vdate;
					} else if ($order->flag == 2) {
						//续费
						$get_date = $company->order_updated_at;
						if ($get_date > time()) {
							$company->order_updated_at = strtotime('+' . $year . ' year', $company->order_updated_at);
						} else {
							$company->order_updated_at = $vdate;
						}
					}

					//开启事务
					DB::beginTransaction();
					try {
						//中间逻辑代码
						$order->save();
						$company->save();
						DB::commit();
						return $pay->success();
					} catch (\Exception $e) {
						//接收异常处理并回滚
						DB::rollBack();
						\log::info('order:' . json_encode($order));
						\log::info('company:' . json_encode($company));
						\Log::info('wxpay:' . json_encode($e));
					}
				}
			}
		} catch (Exception $e) {
			$e->getMessage();
		}

		return $pay->success(); // laravel 框架中请直接 `return $pay->success()`
		\Log::info('微信支付异步回调结束:', ['date' => date('Y-m-d H:i:s')]);
	}
	//微信同步通知方法
	public function wxpay(Request $request) {
		$order_no = $request->input('orderNo');
		if (empty($order_no)) {
			return $this->respond('empty_error');
		}
		$order = Order::where('orderNo', $order_no)->first();
		if (empty($order)) {
			return $this->respond('get_error');
		}
		if ($order->status == 2 && !empty($order->outTradeNo) && !empty($order->validity)) {
			return response()->json(['code' => 200, 'msg' => '支付成功']);
		} else {
			return response()->json(['code' => 500, 'msg' => '未支付']);
		}
	}
	//去支付获取订单信息
	public function orderInfo(Request $request, $id) {
		$order = Order::find($id);
		if (empty($order)) {
			return $this->respond('get_error');
		}
		$get_order_date = strtotime("+1 day", strtotime($order->createdAt));
		if (time() >= $get_order_date) {
			$order->status = 3;
			$order->save();
			return response()->json(['code' => 500, '该订单已关闭']);
		}
		return $this->respond('get_ok', $order);
	}
}
